package com.heima.wemedia.delaytask;

import com.heima.common.delayTask.RedisDelayedQueueUtil;
import com.heima.wemedia.entity.WmNews;
import com.heima.wemedia.service.WmNewsAuditService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RedisDelayedTaskInit {

    @Autowired
    private RedisDelayedQueueUtil delayedQueueUtil;
    @Autowired
    private WmNewsAuditService wmNewsAuditService;
    @Autowired
    private ThreadPoolTaskExecutor  taskExecutor;

    @PostConstruct //spring在启动时会调用当前的方法
    public void initDelayTask(){
//        从延迟队列获取延迟元素
        log.info("======taskinit 执行了");
//            可以周期执行的线程池
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1);

//            固定频率执行任务，周期为每秒一次
        scheduledThreadPool.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                try {
                Object obj = delayedQueueUtil.getFromQueue("wm.news.pub");
                if (obj != null) {
//                  转换数据类型
                    Integer wmNewsId = Integer.valueOf(obj.toString());
                    log.info("===获取到延迟元素wmnewsId={}",wmNewsId);
                    taskExecutor.execute(new Runnable() {
                        @Override
                        public void run() {
                            log.info("===子线程执行 发布任务");
//                  发布文章
                            WmNews wmNews = new WmNews();
                            wmNews.setId(wmNewsId);
                            wmNewsAuditService.publishWmNews(wmNews);
                        }
                    });

                }
                }catch (Exception e){
                    log.error("获取延迟元素失败！");
                    e.printStackTrace();
                }
            }
        }, 0, 1, TimeUnit.SECONDS);

    }
}
